package cn.nexd.collector.wifi;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;

import java.util.List;

import cn.nexd.collector.NexdCollector;
import cn.nexd.collector.NexdCollectorConfiguration;
import cn.nexd.collector.bean.WifiCollectorResult;
import cn.nexd.collector.bean.WifiScannerResultStory;
import cn.nexd.collector.listener.CollectorListener;
import cn.nexd.collector.thread.ThreadPoolManager;

/**
 * Created by codngfish on 16/5/16.
 */
public class WifiCollectorTask extends Wifi {

    private WifiManager wifiManager;
    private final WifiScannerResultStory wifiScannerResultStory;

    public WifiCollectorTask(Context context, NexdCollectorConfiguration collectorConfiguration, CollectorListener collectorListener) {
        super(context, collectorConfiguration, collectorListener);
        wifiScannerResultStory = new WifiScannerResultStory();
    }

    @Override
    public boolean initilazeCollector() {

        collectorRunning = false;
        stop = false;
        if (!permssion()) {
            ThreadPoolManager.getThreadPoolManagerInstance().addTaskToHandlerCollectorEventThreadPool(new HandlerCollectorInterruptThread(NexdCollector.CollectorState.COLLECTOR_INTERRUPT_TYPE_PERMISSION_UNAVAILABLE));
            return false;
        }

        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiManager == null) {
            ThreadPoolManager.getThreadPoolManagerInstance().addTaskToHandlerCollectorEventThreadPool(new HandlerCollectorInterruptThread(NexdCollector.CollectorState.COLLECTOR_INTERRUPT_TYPE_COLLECTOR_UNAVAILABLE));
            return false;
        }

        // wifi 状态为WIFI_STATE_ENABLED 时，表示 wifi 可用。
        // WIFI_STATE_ENABLED wifi 可用
        // WIFI_STATE_DISABLED wifi 已经关闭
        // WIFI_STATE_DISABLING wifi 正在关闭
        // WIFI_STATE_ENABLING wifi 正在打开
        // WIFI_STATE_UNKNOWN wifi 状态未知
        if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_UNKNOWN || wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING || wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED) {
            ThreadPoolManager.getThreadPoolManagerInstance().addTaskToHandlerCollectorEventThreadPool(new HandlerCollectorInterruptThread(NexdCollector.CollectorState.COLLECTOR_INTERRUPT_TYPE_COLLECTOR_UNAVAILABLE));
            return false;
        }
        return true;
    }

    @Override
    public boolean startCollector() {
        stop = false;
        ThreadPoolManager.getThreadPoolManagerInstance().addTaskToHandlerCollectorEventThreadPool(new HandlerCollectorStartThread());
        ThreadPoolManager.getThreadPoolManagerInstance().addTaskToHandlerWifiCollectorLifecycleThreadPool(new WifiScannerThread(), collectorConfiguration.wifi_collector_delay, collectorConfiguration.wifiCollectorRate);
        collectorRunning = true;
        return true;
    }

    @Override
    public boolean stopCollector() {
        collectorRunning = false;
        stop = true;
        return true;
    }

    @Override
    public boolean destroyCollector() {
        //        ThreadPoolManager.getThreadPoolManagerInstance().shutdownWifiCollectorLifecycleThreadPool();
        collectorRunning = false;
        stop = true;
        return true;
    }

    private class HandlerCollectorInterruptThread implements Runnable {
        private NexdCollector.CollectorState collectorState;

        public HandlerCollectorInterruptThread(NexdCollector.CollectorState collectorState) {
            this.collectorState = collectorState;
        }

        @Override
        public void run() {
            collectorListener.onCollectorInterrupt(collectorState);
        }
    }


    private class HandlerCollectorStartThread implements Runnable {
        @Override
        public void run() {
            collectorListener.onCollectionStart();
        }
    }

    private boolean stop = false;

    private class WifiScannerThread implements Runnable {
        @Override
        public void run() {

            if (stop) {
                return;
            }

            if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_UNKNOWN || wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLING || wifiManager.getWifiState() == WifiManager.WIFI_STATE_DISABLED) {
                ThreadPoolManager.getThreadPoolManagerInstance().addTaskToHandlerCollectorEventThreadPool(new HandlerCollectorInterruptThread(NexdCollector.CollectorState.COLLECTOR_INTERRUPT_TYPE_COLLECTOR_UNAVAILABLE));
                //                ThreadPoolManager.getThreadPoolManagerInstance().shutdownWifiCollectorLifecycleThreadPool();
                stopCollector();
                return;
            }

            if (wifiManager != null) {
                wifiManager.startScan();

                //                try {
                //                    Thread.sleep(collectorConfiguration.wifiCollectorRate);
                //                } catch (InterruptedException e) {
                //
                //                }

                List<ScanResult> scanResults = wifiManager.getScanResults();
                wifiScannerResultStory.addWifiCollectorResult(scanResults);
            }

            ThreadPoolManager.getThreadPoolManagerInstance().addTaskStartCollector(new HandlerWifiCollectorListenerThread());
        }
    }

    private int counter = 0;

    protected class HandlerWifiCollectorListenerThread implements Runnable {
        @Override
        public void run() {

            List<WifiCollectorResult> wifiCollectorResults = wifiScannerResultStory.getWifiCollectorResults();
            if (wifiCollectorResults.size() > 4) {
                collectorListener.onCollectionSuccess(wifiCollectorResults);
                counter = 0;
            } else {
                if (counter == 5) {
                    collectorListener.onCollectorFailed(NexdCollector.CollectorState.COLLECTOR_FAILED_TYPE_NO_WIFI_FOUND);
                    counter = 0;
                }
                counter = counter + 1;
            }
        }
    }
}
